package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.query.StrategyQueryObject;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.service.IStrategyService;
import com.github.pagehelper.PageInfo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("regions")
public class RegionController {

    @Autowired
    private IRegionService regionService;
    @Autowired
    private IStrategyService strategyService;

    @Autowired
    private ServletContext servletContext;

    //根据需要的状态返回地点集合
    @GetMapping
   public List<Region> list(Integer state){
        return regionService.listAll(state);
    }

    @GetMapping(value = "{regionId}/strategies",produces = "application/json;charset=utf-8")
    public PageInfo query(StrategyQueryObject qo) throws Exception {
        qo.setPageSize(8);
        return strategyService.query(qo);
    }

    //获取某一地区的所有大攻略
    @GetMapping(value = "{regionId}/strategies",produces = "text/html;charset=utf-8")
   public void listByRegionId(StrategyQueryObject qo, HttpServletResponse response) throws Exception{
        //获取所有当季推荐攻略,状态为推荐,不分页
        qo.setPageSize(0);
        qo.setState(Strategy.STATE_COMMEND);
        PageInfo<Strategy> commends = strategyService.query(qo);
        //获取所有当季攻略,状态无要求,要分页
        qo.setPageSize(8);
        qo.setState(null);
        PageInfo<Strategy> all = strategyService.query(qo);
        //创建配置对象
        Configuration config=new Configuration(Configuration.VERSION_2_3_23);
        //设置模板目录
        config.setDirectoryForTemplateLoading(new File(servletContext.getRealPath("/template")));
        //获取模板
        Template template = config.getTemplate("strategyTemplate.ftl", "utf-8");

        HashMap<Object, Object> data = new HashMap<>();
        data.put("commends",commends);
        data.put("all",all);
        //合成结果
        template.process(data,response.getWriter());
    }
}
